package network;

import java.io.IOException;
import java.net.*;
import java.util.Scanner;

public class UdpEchoClient {
    DatagramSocket socket =null;
    String serverIP;
    int serverPort;
    public UdpEchoClient(String serverIp,int serverPort) throws SocketException {
        this.serverIP=serverIp;
        this.serverPort=serverPort;
        socket=new DatagramSocket();
    }
    public void start() throws IOException {
        System.out.println("客户端启动");
        Scanner scanner =new Scanner(System.in);
        while(true){
            System.out.print("->");
            //要做四件事
            //1.从控制台上读取要发送的请求
            if(!scanner.hasNext()){
                break;
            }
            String request =scanner.next();
            //2.构造请求并发送
            DatagramPacket requestPacket = new DatagramPacket(request.getBytes(),request.getBytes().length,
                    InetAddress.getByName(serverIP),serverPort);
            socket.send(requestPacket);
            //3.读取服务器的响应
            DatagramPacket reponsePacket = new DatagramPacket(new byte[4096],4096);
            socket.receive(reponsePacket);
            //4.把响应显示到控制台上
            String reponse = new String(reponsePacket.getData(),0,reponsePacket.getLength());
            System.out.println(reponse);
        }
    }

    public static void main(String[] args) throws IOException {
        UdpEchoClient Client =new UdpEchoClient("127.0.0.1",9090);
        Client.start();
    }
}
